
// @ts-ignore;
import React, { useState, useEffect } from 'react';
// @ts-ignore;
import { Button, Card, CardHeader, CardTitle, CardDescription, CardContent } from '@/components/ui';
// @ts-ignore;
import { ArrowLeft, Info, User, Image as ImageIcon } from 'lucide-react';

export default function Profile(props) {
  const {
    $w
  } = props;
  const [selectedArtwork, setSelectedArtwork] = useState(null);
  const [artworks, setArtworks] = useState([]);
  const [loading, setLoading] = useState(true);
  const [userData, setUserData] = useState({
    name: '未命名用户',
    avatar: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=500&auto=format&fit=crop',
    bio: '暂无个人简介'
  });

  // 获取用户作品数据
  useEffect(() => {
    const fetchData = async () => {
      try {
        // 获取当前用户信息
        if ($w.auth.currentUser) {
          setUserData({
            name: $w.auth.currentUser.nickName || $w.auth.currentUser.name || '未命名用户',
            avatar: $w.auth.currentUser.avatarUrl || 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=500&auto=format&fit=crop',
            bio: '暂无个人简介'
          });
        }

        // 获取用户作品
        const result = await $w.cloud.callDataSource({
          dataSourceName: 'artwork',
          methodName: 'wedaGetRecordsV2',
          params: {
            filter: {
              where: {
                user_id: {
                  $eq: $w.auth.currentUser?.userId || ''
                },
                is_generating: {
                  $eq: false
                }
              }
            },
            select: {
              $master: true
            },
            orderBy: [{
              created: 'desc'
            }],
            pageSize: 20
          }
        });
        setArtworks(result.records || []);
      } catch (error) {
        console.error('获取数据失败:', error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [$w.auth.currentUser?.userId, $w.cloud]);

  const handleBack = () => {
    $w.utils.navigateBack();
  };

  return (
    <div className="relative min-h-screen bg-gray-100">
      {/* 返回按钮 */}
      <button 
        onClick={handleBack}
        className="absolute top-6 left-6 bg-white bg-opacity-90 hover:bg-opacity-100 p-3 rounded-full shadow-lg transition-all z-10"
      >
        <ArrowLeft className="text-gray-800" />
      </button>

      {/* 个人资料头部 */}
      <div className="relative bg-gradient-to-r from-purple-600 to-purple-500 pt-20 pb-12 px-6">
        <div className="max-w-4xl mx-auto flex flex-col md:flex-row items-center">
          <div className="w-32 h-32 rounded-full border-4 border-white overflow-hidden mb-4 md:mb-0 md:mr-8 shadow-lg">
            <img 
              src={userData.avatar} 
              alt="用户头像" 
              className="w-full h-full object-cover"
            />
          </div>
          <div className="text-center md:text-left text-white">
            <h1 className="text-3xl font-bold mb-2">{userData.name}</h1>
            <p className="text-lg opacity-90 mb-4">{userData.bio}</p>
            <div className="flex justify-center md:justify-start space-x-4">
              <span className="bg-white bg-opacity-20 px-4 py-1 rounded-full">
                {artworks.length} 作品
              </span>
              <span className="bg-white bg-opacity-20 px-4 py-1 rounded-full">
                0 粉丝
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* 主要内容区 */}
      <div className="max-w-4xl mx-auto px-6 py-8 -mt-10 relative z-0">
        {/* 作品展示区 */}
        <div className="mb-8">
          <h2 className="text-2xl font-bold text-gray-800 mb-6 flex items-center">
            <ImageIcon className="mr-2 text-purple-600" />
            我的作品
          </h2>
          
          {loading ? (
            <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
              {[...Array(6)].map((_, i) => (
                <div key={i} className="bg-gray-200 rounded-xl h-48 animate-pulse"></div>
              ))}
            </div>
          ) : artworks.length === 0 ? (
            <div className="bg-white rounded-xl p-8 text-center">
              <p className="text-gray-500 mb-4">您还没有创作任何作品</p>
              <Button 
                onClick={() => $w.utils.navigateTo({ pageId: 'studio' })}
                className="bg-purple-600 hover:bg-purple-700"
              >
                去创作
              </Button>
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {artworks.map(artwork => (
                <div 
                  key={artwork._id}
                  onClick={() => setSelectedArtwork(artwork)}
                  className="bg-white rounded-xl overflow-hidden shadow-md cursor-pointer transition-all hover:shadow-lg hover:-translate-y-1"
                >
                  <div className="h-48 overflow-hidden">
                    <img 
                      src={artwork.image} 
                      alt={artwork.title} 
                      className="w-full h-full object-cover"
                    />
                  </div>
                  <div className="p-4">
                    <h3 className="font-semibold text-gray-800 mb-1 truncate">{artwork.title}</h3>
                    <p className="text-sm text-gray-600">
                      {new Date(artwork.created).toLocaleDateString()}
                    </p>
                    <div className="flex mt-2">
                      <span className="text-xs bg-purple-100 text-purple-800 px-2 py-1 rounded">
                        {artwork.style_name}
                      </span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 社交链接 */}
        <div className="bg-white rounded-xl p-6 shadow-md">
          <h2 className="text-2xl font-bold text-gray-800 mb-4 flex items-center">
            <User className="mr-2 text-purple-600" />
            联系我
          </h2>
          <div className="flex flex-wrap gap-3">
            <Button variant="outline" className="border-gray-300 hover:bg-gray-50">
              微博
            </Button>
            <Button variant="outline" className="border-gray-300 hover:bg-gray-50">
              微信
            </Button>
            <Button variant="outline" className="border-gray-300 hover:bg-gray-50">
              Email
            </Button>
          </div>
        </div>
      </div>

      {/* 作品详情弹窗 */}
      {selectedArtwork && (
        <div className="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center p-4 z-50">
          <Card className="w-full max-w-md">
            <CardHeader>
              <CardTitle>{selectedArtwork.title}</CardTitle>
              <CardDescription>
                {new Date(selectedArtwork.created).toLocaleDateString()}
              </CardDescription>
            </CardHeader>
            <CardContent>
              <img 
                src={selectedArtwork.image} 
                alt={selectedArtwork.title}
                className="w-full rounded-lg mb-4"
              />
              <div className="grid grid-cols-2 gap-4 mb-4">
                <div>
                  <p className="text-sm font-medium text-gray-500">艺术风格</p>
                  <p>{selectedArtwork.style_name}</p>
                </div>
                <div>
                  <p className="text-sm font-medium text-gray-500">风格参数</p>
                  <p>{selectedArtwork.style_params}</p>
                </div>
              </div>
              <p className="text-gray-700 mb-4">{selectedArtwork.description}</p>
              <Button 
                onClick={() => setSelectedArtwork(null)}
                className="w-full bg-purple-600 hover:bg-purple-700"
              >
                关闭
              </Button>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  );
}
